02. Namespaces

Namespaces

C++ vector syntax is a little bit hard to read especially because you have to type std over and over again: like for example, std::cout or std::string or std::vector.

Thankfully, C++ provides a way to avoid writing std all the time.

Std is something called a namespace. Without getting too much into the details, namespaces let you organize code into logical groups. In this case, std is the namespace for the Standard Library.

You can actually declare your namespace at the top of your main.cpp file and then avoid writing

std::

over and over again. Here is an example:

#include <iostream>
#include <vector>
using namespace std;

int main() {
    vector<int> intvectorvariable;
    int intvariable = 5;
    cout << intvariable << endl;
    return 0;

}

Now, the vector declaration, cout and endl no longer needed std::.

Benefits of Namespaces

Declaring the namespace makes the code easier to read and write. The downside is that you have to be careful with how you name your own variables and functions. Previously, you might have written:

std::cout

which lets your program know that you meant the cout function from the standard library.

C++ would have let you actually create a variable or function named cout as well. That's probably not a good idea, but the code won't produce an error. Once you declared the std namespace, your cout variable or function would be in conflict with the standard library cout.

Going forward from this point, the exercises and code examples will include the using namespace std; line of code.

Name Spaces

Mark all of the statements that are true about name spaces:

SOLUTION:
  • Namespaces help group related code together.
  • Namespaces can help avoid conflicts between variable names, function names and class names.
  • Declaring a namespace in your program's header allows you to avoid writing out the namespace name multiple times in your code.

You can now simplify the vector syntax using namespaces. Let's compare Python list and C++ vector syntax and then practice coding C++ vectors.

Namespace Practice

Use the standard library namespace and change the code so that the code no longer uses "std::".

Start Quiz:

#include <iostream>
#include <string>

// TODO: Use the standard namespace

int main() {
    
    // TODO: change the code so that it no longer uses "std::"    
    
    std::string fruit = "apple";
    std::string vegetable = "broccoli";
    
    std::cout << "My favorite fruit is " << fruit <<
      " and my favorite vegetable is " << vegetable << "\n";
    
    return 0;
}
#include <iostream>
#include <string>

using namespace std;

int main() {
    
    string fruit = "apple";
    string vegetable = "broccoli";
    
    cout << "My favorite fruit is " << fruit <<
      "and my favorite vegetable is " << vegetable << "\n";
    
    return 0;
}